/*
 * @Descripttion: 检查记录详情
 * @version: 
 * @Author: linPing
 * @Date: 2019-10-29 12:25:00
 * @LastEditTime: 2019-11-04 17:12:53
 */



import React, { Fragment } from 'react';

import { observer, inject } from 'mobx-react';
import NavigationBar from '../../common/NavigationBar';
import GlobalStyles from "../../res/styles/GlobalStyles";

import SafeAreaViewPlus from "../../common/SafeAreaViewPlus";
import Toast, { DURATION } from 'react-native-easy-toast';
import VisibleView from "../../common/VisibleView";
import NavigationUtil from '../../navigator/NavigationUtil'
import ViewUtil from "../../util/ViewUtil";
import AsyncStorageUtils from "../../expand/AsyncStorage";
import { SwipeListView, SwipeRow } from 'react-native-swipe-list-view';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
    View,
    Text,
    Linking,
    Alert,
    StatusBar,
    Image,
    DeviceEventEmitter,
    FlatList,
    TouchableHighlight

} from 'react-native';
import { Button } from "react-native-elements"
// import { TouchableOpacity } from 'react-native-gesture-handler';



@inject('appStore')
@observer
export default class TaskDetailPage extends React.Component {
    constructor(props) {
        super(props)
        this.title = "检查记录详情"
        this.params = this.props.navigation.state.params
        this.originalData = this.params.item

        this.state = {
            startCheck: false,
            isShowInfo: true,
            selectedIndex: 0,
            showDel: false,
            hiddenList: [],
            highlight:[],
            loaded:false,
        }

        const TaskKey = this.props.appStore.TaskKey
        const RoomId = this.originalData.id
        this.key = `${TaskKey}-${RoomId}`

    }

    genQuickAction(data) {
        return <View>
            <TouchableHighlight>
                <View>
                    <Text>删除</Text>
                </View>
            </TouchableHighlight>
        </View>
    }
    _renderItem(data) {
        const { item } = data

        return <TouchableOpacity
        // onPress={() => {
        //     NavigationUtil.goPage({ item }, "TaskRoomList")
        // }}

        >
            <View style={[styles.itemBox]}>
                <View style={styles.row}>
                    <Text style={styles.title}>{item.title}</Text>
                    {data.item.status === 0 && <Text style={[styles.itemText, GlobalStyles.status.warning]}>未完成</Text>}
                    {data.item.status === 1 && <Text style={[styles.itemText, GlobalStyles.status.success]}>已完成</Text>}
                </View>
                <View style={styles.row}>
                    <View style={styles.rowItem}>
                        <Text style={[styles.itemText, GlobalStyles.marginRight10]}>房间检查进度</Text>
                        <Text style={styles.itemText}>{item.completeTotal}/{item.roomTotal}</Text>
                    </View>
                </View>
                <View style={GlobalStyles.line} />
            </View>

        </TouchableOpacity>
    }


    onBack = () => {
        this.setState({
            showDel: false,
        })
        NavigationUtil.goBack(this.props.navigation);
    }

    highLightClick = () => {

    }
    addHiddenClick (type,item) {
        
        const TaskKey = this.props.appStore.TaskKey
        const RoomId = this.originalData.id
        const {highlight} = this.state
        let params={
            type:type,//{0:亮点,1:隐患}
            // mode:"add", //{"add",'edit'}
            key:`${TaskKey}-${RoomId}`,
            item:highlight.length&& type===0?highlight[0]:item
        }
        NavigationUtil.goPage(params, "TaskCheck")
    }
    deleteHidden(id) {
    
        Alert.alert('确认', '确认删除此条数据？',
            [{ text: '取消', onPress: () => { console.log('取消') } },
            {
                text: '确定',
                onPress: () => {
                    AsyncStorageUtils.deleteId(this.key,id)
                    this.initData()
                }
            }])

    }
    initData(){
   
        AsyncStorageUtils.getAllDataForKey(this.key).then(data=>{
            this.setState({
                hiddenList:data.filter(item=>item.type===1),
                highlight:data.filter(item=>item.type===0),
                loaded:true,
            })
            if(this.state.hiddenList.length>0){
                this.setState({
                    startCheck:true
                })
            }
        })
 
     
    
        
        setTimeout(() => {
            this.setState({
                showDel: true,
            })

        }, 200)
    }
    componentDidMount() {
        this.initData()

        this.refreshSubScription = DeviceEventEmitter.addListener('refresh',(message)=>{
            this.toast.show('保存成功', 800)
            if(message){
              
              this.initData()
               
            }
        })
    }
    componentWillUnmount(){
        this.refreshSubScription.remove();
    }
    genID(length){

        return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
      
      }
  
    initInsectionRecord() {
        this.setState({
            startCheck: true
        })
        
        // this.originalData
        //const key = this.props.appStore.TaskKey
        //const roomId = this.genID(32)
       
        //AsyncStorageUtils.saveById(key,roomId,{...this.originalData,highlight:{checkId:"",items:["A"]},hidden_danger:{checkId:"",items:["A","B","c"]}})


    }
    onSubmit(){

    }

    showData(){
        const key = this.props.appStore.TaskKey
        const roomId = this.originalData.id
        // AsyncStorageUtils.loadById(key,roomId).then(data=>{
        //     console.log(data)
        //     NavigationUtil.goPage({data},"ShowDataPage")
        // })
        AsyncStorageUtils.getAllDataForKey(this.key).then(data=>{
            // AsyncStorageUtils.load(data[0]).then(data=>{
            //     console.log(data)
            //     NavigationUtil.goPage({data},"ShowDataPage")
            // })
            NavigationUtil.goPage({data},"ShowDataPage")
        })
    }
    clearData(){
    
        AsyncStorageUtils.clearMapForKey(this.key)
        // AsyncStorageUtils.deleteId(key,id)
    }

    render() {
        const { navigation } = this.props
        const { appStore, appStore: { theme } } = this.props

        let statusBar = {
            backgroundColor: theme,
            barStyle: 'light-content',
        };
        let navigationBar =
            <NavigationBar
                title={this.title}
                statusBar={statusBar}
                leftButton={ViewUtil.getLeftBackButton(() => this.onBack())}
                rightButton={ViewUtil.getRightButton("提交", () => this.onSubmit())}
                style={{ backgroundColor: theme }}
            />;

        const item = this.originalData

        return (


            <SafeAreaViewPlus style={GlobalStyles.root_container}>
                {navigationBar}
                <Button
                    title={"清除数据"}
                    onPress={()=>this.clearData()}
                ></Button>
                <Button
                    title={"显示数据"}
                    onPress={()=>this.showData()}
                ></Button>
                <ScrollView>
                    <View style={[styles.header_container]}>
                        <View style={styles.row}>
                            <Text style={styles.title}>{item.title}</Text>
                            {item.status === 0 && <Text style={[styles.itemText, GlobalStyles.status.warning]}>未检查</Text>}
                            {item.status === 1 && <Text style={[styles.itemText, GlobalStyles.status.success]}>待提交</Text>}
                            {item.status === 1 && <Text style={[styles.itemText, GlobalStyles.status.success]}>已提交</Text>}
                        </View>
                        {this.state.isShowInfo && <View style={GlobalStyles.line} />}
                        {this.state.isShowInfo && <View style={styles.info}>
                            <View style={styles.row}>
                                <Text style={[styles.itemLabel]}>安全等级</Text>
                                <Text style={styles.itemText}>{item.level}级</Text>
                            </View>

                            <View style={styles.row}>
                                <Text style={[styles.itemLabel]}>所属楼宇</Text>
                                <Text style={styles.itemText}>{item.buildName}</Text>
                            </View>
                            <View style={styles.row}>
                                <Text style={[styles.itemLabel]}>所属学院</Text>
                                <Text style={styles.itemText}>{item.collegName}</Text>
                            </View>
                            <View style={styles.row}>
                                <Text style={[styles.itemLabel]}>所属实验室</Text>
                                <Text style={styles.itemText}>{item.labName}</Text>
                            </View>
                            <View style={styles.row}>
                                <Text style={[styles.itemLabel]}>学院负责人</Text>
                                <Text style={styles.itemText}>{item.collegManager}</Text>
                            </View>
                            <View style={styles.row}>
                                <Text style={[styles.itemLabel]}>房间负责人</Text>
                                <View style={styles.row}>

                                    <Button

                                        onPress={() => {
                                            let tel = `tel:${item.managerTel}`

                                            Alert.alert('确认', '拨打房间负责人电话？',
                                                [{ text: '取消', onPress: () => { console.log('取消') } },
                                                {
                                                    text: '确定',
                                                    onPress: () => {
                                                        Linking.canOpenURL(tel).then((supported) => {
                                                            if (!supported) {

                                                                console.log('Can not handle tel:' + tel)
                                                            } else {

                                                                return Linking.openURL(tel)
                                                            }
                                                        }).catch(error => console.log('tel error', error))
                                                    }
                                                }])
                                        }}
                                        title="联系房间负责人"
                                        type="clear"
                                        buttonStyle={{ height: 20 }}
                                        titleStyle={{ fontSize: 12 }}
                                    />
                                    <Text style={styles.itemText}>{item.managerName}</Text>
                                </View>

                            </View>

                            <View style={styles.rowItem}>
                                <Text style={[styles.itemLabel, GlobalStyles.marginRight10]}>备注</Text>
                                <Text style={[styles.itemText, styles.textArea]}>{item.remark}</Text>
                            </View>

                        </View>
                        }

                        <View style={GlobalStyles.line} />

                        <View>
                            <TouchableOpacity
                                onPress={() => {
                                    this.setState({
                                        isShowInfo: !this.state.isShowInfo
                                    })
                                }}
                            >
                                <View style={{ padding: 10 }}>
                                    {this.state.isShowInfo && <Text style={{ textAlign: "center", fontSize: 11, color: "#999" }}>收起房间详情</Text>}
                                    {!this.state.isShowInfo && <Text style={{ textAlign: "center", fontSize: 11, color: "#999" }}>展开房间详情</Text>}
                                </View>

                            </TouchableOpacity>
                        </View>


                    </View>
                    {this.state.startCheck &&  <View>

                         {ViewUtil.getCustomItem(() => this.addHiddenClick(0), "亮点")}
                        <View style={styles.list_container}>

                           
                            
                            <SwipeListView
                                useFlatList
                                data={this.state.highlight}
                                renderItem={(data, rowMap) => (
                                    <TouchableHighlight onPress={() => {
                                        // console.log(data, rowMap)
                                        this.addHiddenClick(0,data&&data.item)
                                    }}>
                                        <View style={styles.rowFront}>
                                            <Text style={{ color: '#666',paddingRight:10 ,flex:1,  lineHeight:22}}>{data.item.desc || ""}</Text>
                                            { data.item.images[0] && <Image
                                                source={{ uri: data.item.images[0] || '' }}
                                                style={{ width: 75, height: 75 }}
                                            />}
                                        </View>
                                    </TouchableHighlight>
                                )}
                                renderHiddenItem={(data, secId, rowId, rowMap) => {
                                   
                                    return (

                                        <View style={styles.rowBack} >
                                            <Text></Text>
                                            <TouchableOpacity onPress={_ => this.deleteHidden(data.item.key)}>
                                                {this.state.showDel && <Text style={{ flex: 1, width: 100, textAlignVertical: 'center', backgroundColor: "red", color: "#fff", textAlign: 'center' }}>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;删除</Text>}
                                            </TouchableOpacity>
                                        </View>

                                    )
                                }}

                                disableRightSwipe={true}
                                rightOpenValue={-75}
                                stopRightSwipe={-100}
                            />


                        </View>

{ViewUtil.getCustomItem(() => this.addHiddenClick(1), "隐患列表", 'ios-add', 24)}
                        <View style={styles.list_container}>

                            


                            <SwipeListView
                                useFlatList
                                data={this.state.hiddenList}


                                renderItem={(data, rowMap) => (
                                    <TouchableHighlight onPress={() => {
                                        console.log(data)
                                        console.log(data.item)
                                        this.addHiddenClick(1,data.item)
                                    }}>
                                        <View style={styles.rowFront}>
                                            <Text style={{ color: '#666',paddingRight:10 ,flex:1,  lineHeight:22,}}>{data.item.checkItem.name || ""}</Text>
                                           { data.item.images[0] && <Image
                                                source={{ uri: data.item.images[0] || '' }}
                                                style={{ width: 75, height: 75 }}
                                            />}
                                        </View>
                                    </TouchableHighlight>
                                )}
                                renderHiddenItem={(data, secId, rowId, rowMap) => {
                                    
                                    return (

                                        <View style={styles.rowBack} >
                                            <Text></Text>
                                            <TouchableOpacity onPress={_ => this.deleteHidden(data.item.key)}>
                                                {this.state.showDel && <Text style={{ flex: 1, width: 100, textAlignVertical: 'center', backgroundColor: "red", color: "#fff", textAlign: 'center' }}>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;删除</Text>}
                                            </TouchableOpacity>
                                        </View>

                                    )
                                }}

                                disableRightSwipe={true}
                                rightOpenValue={-75}
                                stopRightSwipe={-100}
                            />


                        </View>
                    </View>}
                    {!this.state.startCheck && this.state.loaded  && <View style={{ alignItems: "center", padding: 20 }}>
                        <Button
                            title="开始检查"
                            onPress={() => {
                                this.initInsectionRecord()
                            }}
                            buttonStyle={{ width: 200, height: 40 }}
                            titleStyle={{ fontSize: 16 }}
                        ></Button>
                    </View>}
                </ScrollView>
                <Toast
                        ref={o=>this.toast=o}
                        position={'bottom'}
                        positionValue={130}
                        fadeInDuration={800}
                        fadeOutDuration={400}
                        opacity={0.7}
                    />
            </SafeAreaViewPlus>


        )
    }

};

const styles = StyleSheet.create({


    outView: {
        flex: 1,
        marginTop: 22
    },
    rowBack: {
        alignItems: 'center',

        flexDirection: 'row',
        justifyContent: 'space-between',
        flex: 1
    },
    rowFront: {
        alignItems: "flex-start",
        backgroundColor: '#fff',
        flexDirection: "row",
        justifyContent: "space-between",
        padding: 10,
        paddingHorizontal: 20,
        paddingBottom:10,
      
        minHeight: 20,
        overflow: 'hidden'

    },
    leftView: {
        width: 75,
        alignItems: 'center',
        backgroundColor: 'green',
        height: 50,
        justifyContent: 'center'
    },

    container: {
        flex: 1
    },
    header_container: {
        padding: 20,
        paddingBottom: 0,
        backgroundColor: '#fff',
        marginBottom: 20
    },
    info: { paddingTop: 20, marginBottom: 20 },
    itemBox: {

        paddingVertical: 2,
        backgroundColor: '#fff',
        marginBottom: 10,

    },
    title: {
        color: "#333"
    },
    row: {

        alignItems: 'center',
        flexDirection: "row",
        justifyContent: "space-between",
        marginBottom: 10
    },
    itemText: {

        fontSize: 12,
        color: "#666"
    },
    textArea: {
        flex: 1,
        textAlign: "right",
    },
    desc: {
        fontSize: 11,
        color: "#aaa"
    },
    rowItem: {
        flexDirection: "row",
    },
    list_container: {
        // padding: 20,
        marginBottom: 20,
        paddingVertical: 0,
        marginTop:0.5,
        // paddingBottom: 20,
        backgroundColor: '#fff'
    },
    list_title: {
        backgroundColor: '#fff',
        marginBottom: 10,
    },
    itemLabel: {
        fontSize: 12,
        color: "#aaa"
    }


});

